#include "heap.h"
#include <stdio.h>

int left(int i) 
{
	return 2 * i; 
}

int right(int i)
{
	return 2 * i + 1;
}

int swap_value(int *vala, int *valb)
{
	int t;
	t = *vala; 
	*vala = *valb;
	*valb = t;
	return 1;
}

int check_heap(int *heap, int len, int i)
{
	int l = left(i);
	int r = right(i);
	int max = i;
	
	if(l < len && heap[l-1] > heap[i-1]) 
	{
		max = l;	
	}
	
	if(r < len && heap[r-1] > heap[max-1]) 
	{
		max = r;
	}
	
	if(i != max) 
	{
		swap_value(&heap[i-1], &heap[max-1]);
		check_heap(heap, len, max);
	}

	return 1;
}

int build_heap(int *heap, int len) 
{
	int start = len / 2;
	while(start>=0) 
	{
		check_heap(heap, len, start);
		start--;
	}
	return 0;
}

int sort_heap(int *heap, int len)
{
	int i = 0;
	printf("5: %d \n", heap[5]);
	for(; i<len; i++)
	{
		build_heap(heap, len - i);
		swap_value(&heap[0], &heap[len-i-1]);

	}
	
	return 1;
}

